package com.exercises;

import java.util.Arrays;

public class Exercise31 {

    public static void main(String[] args) {
        int[] nums = new int[]{1, 3, 2};
        new Exercise31().nextPermutation(nums);
        System.out.println(Arrays.toString(nums));
    }

    public void nextPermutation(int[] nums) {
        if (nums.length > 1) {
            int i = nums.length - 2;
            while (i >= 0 && nums[i] >= nums[i + 1]) {
                i--;
            }
            if (i == -1) {
                Arrays.sort(nums);
                return;
            }

            int min = nums[i];
            int max = nums[i];
            int j = i + 1;
            for (; j < nums.length; j++) {
                if (nums[j] > min) {
                    max = nums[j];
                } else {
                    break;
                }
            }
            nums[i] = max;
            nums[j - 1] = min;

            Arrays.sort(nums, i + 1, nums.length);
        }
    }
}
